package com.kangjia.api.dao;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

import org.bson.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.fasterxml.jackson.databind.JsonNode;
import com.kangjia.api.condition.MongoReportCondition;
import com.kangjia.util.JsonNodeUtil;
import com.mongodb.BasicDBObject;
import com.mongodb.Block;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;

import lombok.extern.slf4j.Slf4j;

/**
 * 康加报告数据保存mongodb
 * 
 * @author sunshulin
 *
 */
@Repository
@Slf4j
public class KangjiaMongoDao {

	private MongoCollection<Document> kangjiaReport;

	@Autowired
	public KangjiaMongoDao(MongoDatabase mdb) {
		kangjiaReport = mdb.getCollection("kangjia_report");
	}

	public void saveData(JsonNode jsonNode, String id) {
		log.info("保存原始报告数据到mongo db id={}", id);
		Document document = Document.parse(jsonNode.toString());
		document.put("_id", id);
		LocalDateTime ldt = LocalDateTime.parse(JsonNodeUtil.string(jsonNode, "inspectDate"), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
		document.put("crtime", ldt.toInstant(ZoneOffset.of("+8")).toEpochMilli());
		kangjiaReport.insertOne(document);
	}
	
	public void updateData(JsonNode jsonNode, String id) {
		log.info("更新原始报告数据到mongo db id={}", id);
		Document document = Document.parse(jsonNode.toString());
		LocalDateTime ldt = LocalDateTime.parse(JsonNodeUtil.string(jsonNode, "inspectDate"), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
		document.put("crtime", ldt.toInstant(ZoneOffset.of("+8")).toEpochMilli());
		kangjiaReport.replaceOne(new Document("_id", id), document);
	}

	public Document findOne(MongoReportCondition mrc) {
		List<Document> list = findData(mrc);
		return list.isEmpty() ? null : list.get(0);
	}
	
	public List<Document> findData(MongoReportCondition mrc) {
		log.info("查找原始报告数据 mrc={}", mrc);
		List<Document> list = new ArrayList<>();
		FindIterable<Document> finds = kangjiaReport.find(mrc.createCondition()).sort(new BasicDBObject("crtime", 1))
				.limit(mrc.getLimit());
		finds.forEach(new Block<Document>() {
			public void apply(Document _doc) {
				list.add(_doc);
			}
		});
		return list;
	}
}
